const express = require("express");
//引入路由器
const userRouter = require("./routers/user.js");
const goodsRouter = require("./routers/goods.js");
const cartRouter = require("./routers/cart.js");
const orderRouter = require("./routers/order.js");
const homeRouter = require('./routers/home.js');

const addressRouter = require('./routers/address');
const photoRouter = require('./routers/photo');

const multerUpload = require('./routers/upload');

const session = require("express-session");
const cors = require('cors');
const token = require('./util/token.js');
const Token = require("./util/token");
const response = require("./routers/response");

const app = express();

let corsOptions = {
    origin: [/http/, "http://localhost:80"], //数组元素可以是字符串，正则表达式
    credentials: true,
    optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(cors(corsOptions));

/*
可以在这里做所有接口的用户token验证，这样就不需要在每个接口中重复验证代码了
const whiteListUrl = { // 白名单 不需要做校验的接口
  get: [
    "/index/carousel",
    "/uploads/goods/swiper",
    "/user/islogin"
  ],
  post: [
    "/user/login"
  ]
}

const hasOneOf = (path, arr) => {
  //return arr.some(item => item.includes(path))
  return arr.some(item => path.includes(item))
}

app.all('*', (req, res, next) => {
  let method = req.method.toLowerCase() // 获取当前请求方式
  let path = req.path // 获取当前请求路径
  console.log(path);

  if (whiteListUrl[method] && hasOneOf(path, whiteListUrl[method])) {
    next() // 过滤 有些接口不需要做Token校验
  }
  else { // 需要校验的接口
    const token = req.headers.authorization // 取到请求头中Token


    let result = token(token);
    if(result.code == 1){
        req.userInfo = result.data.nameuserInfo;
        next();
    }else{
      res.send({
        code: result.code,
        msg: result.msg,
        data: result.data
      });

    }
  }
});

*/


app.use(express.json()); //在其他路由中间件前（尽可能靠前，以能够通过bodyPaser获取req.body）
app.use(express.urlencoded({extended: false}));
// 使用 session 中间件
app.use(session({
    secret: 'zjffapp',// 对session id 相关的cookie 进行签名
    name: 'xz-app',   //这里的name值得是cookie的name，默认cookie的name是：connect.sid
    resave: false,
    saveUninitialized: true, // 是否保存未初始化的会话
    cookie: {
        maxAge: 1000 * 60 * 10, // 设置 session 的有效时间，单位毫秒
    },
}));

//托管静态资源
app.use(express.static("public"));

function excludeUrl(url) {
    let urls = ["/user/islogin", "/user/login", "/welcome","/uploads","user/register"]
    let flag = false
    urls.forEach(u => {
        let b = url.indexOf(u);
        flag |= (b !== -1)
    })
    return flag;
}

app.all("/*", function (req, res, next) {
    let url = req.url;
    let token = req.headers.authorization;
    if (url === "/" || excludeUrl(url)) {
        next()
    } else if (token != undefined && Token.verify(token).code == 1) {
        next()
    } else {
        console.log(url)
        res.send(response.authorizeEx())
        res.end()
    }
})

//注册路由,建议放在其他中间件的后面
app.use("/user", userRouter);
app.use("/goods", goodsRouter);
app.use("/cart", cartRouter);
app.use("/order", orderRouter);
app.use("/home", homeRouter);
app.use("/address", addressRouter);
app.use("/photo", photoRouter);

app.use('/upload', multerUpload);

const port = 5050;
app.listen(port, () => console.log(`Shop App listening on port:${port}`));
